import React, { useRef } from 'react'
import store from '../../redux/store'
import {createIncrementAction, createDecrementAction} from '../../redux/countAction'

function Count() {
  const selectNumberRef = useRef()

  /**
   * 加
   */
  const increment = () => {
    const { value } = selectNumberRef.current
    store.dispatch(createIncrementAction(value * 1))
  }

  /**
   * 减
   */
  const decrement = () => {
    const { value } = selectNumberRef.current
    store.dispatch(createDecrementAction(value * 1))
  }

  /**
   * 如果为奇数，则加
   */
  const incrementIfOdd = () => {
    const { value } = selectNumberRef.current
    const count = store.getState()
    if(count % 2 !== 0) {
      store.dispatch(createIncrementAction(value * 1))
    }
  }

  /**
   * 异步延迟加
   */
  const incrementIfAsync = () => {
    const { value } = selectNumberRef.current
    setTimeout(() => {
      store.dispatch(createIncrementAction(value * 1))
    }, 500)
  }

  return (
    <div style={{ width: 500, margin: '0 auto' }}>
      <h1>当前求和为：{store.getState()}</h1>
      <select ref={selectNumberRef}>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
      </select>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
      <button onClick={incrementIfOdd}>当前求和为奇数再加</button>
      <button onClick={incrementIfAsync}>异步加</button>
    </div>
  )
}

export default Count
